package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.service.AddressBookService;
import com.sky.mapper.AddressBookMapper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author 86158
* @description 针对表【address_book(地址簿)】的数据库操作Service实现
* @createDate 2025-08-25 15:46:19
*/
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>
    implements AddressBookService{
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public boolean setDefault(AddressBook addressBook) {
        // 防御性校验：确保要设为默认的地址 ID 存在
        if (addressBook.getId() == null) {
            // 根据业务决定：抛异常 / 返回 false
            throw new IllegalArgumentException("设置默认地址失败，地址 ID 为空");
        }

        // 1. 将当前用户所有地址设为非默认（is_default=0）
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId())
                .set(AddressBook::getIsDefault, 0);
        log.error(String.format("更新用户[%d]地址失败", BaseContext.getCurrentId()));
        boolean updateAllNonDefault = this.update(wrapper);
        if (!updateAllNonDefault) {
            // 批量更新失败，可记录日志或抛异常
            log.error(String.format("更新用户[%d]地址失败", BaseContext.getCurrentId()));
            return false;
        }

        // 2. 将目标地址设为默认（is_default=1）
        LambdaUpdateWrapper<AddressBook> wrapper2 = new LambdaUpdateWrapper<>();
        wrapper2.eq(AddressBook::getId, addressBook.getId())
                .eq(AddressBook::getUserId, BaseContext.getCurrentId())
                .set(AddressBook::getIsDefault, 1);
        return this.update(wrapper2);
    }
}




